import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:life_milestones/MS-Model/MS-User.dart';
import 'package:life_milestones/MS-global-url.dart';
import 'package:life_milestones/MS-request.dart';
import 'package:life_milestones/controller/MS-global-user-controller.dart';
import 'package:life_milestones/util/MS-config-info-util.dart';
import 'package:life_milestones/util/MS-log-util.dart';
import 'package:life_milestones/util/MS-toast-util.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
class MSLoginPage extends StatefulWidget {
  const MSLoginPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MSLoginPageState();
  }
}

class _MSLoginPageState extends State<MSLoginPage> {
  TapGestureRecognizer term = TapGestureRecognizer();
  TapGestureRecognizer privacy = TapGestureRecognizer();
  bool isAgree = false;
  @override
  void initState() {
    super.initState();
    MSLog.addEvent(page:MSLogPages.LoginPage);
  }

  @override
  void dispose() {
    term.dispose();
    privacy.dispose();
    super.dispose();
  }

  Future<bool> loginByFast(MSGlobalUserController controller) async {
    if (checkIsAgree()) {
      try {
        showLoading();
        var token = MSConfigInfoUtil().deviceId;
        var response = await MSRequest().postForm<Map<String, dynamic>>(
            MSGlobalUrl.login,
            data: {"oauthType": "4", "token": token});
        if (response != null &&
            response["code"] == 0 &&
            response["data"] != null) {
          controller.token = response["data"]["token"];
          var user = MSUser.fromJson(response["data"]["userInfo"]);
          controller.user = user;
          MSLog.addEvent(page:MSLogPages.LoginSuccess);
          hideLoading();
          return true;
        }
      } catch (e) {
        hideLoading();
        return false;
      }
    }
    return false;
  }

  bool checkIsAgree() {
    if (!isAgree) {
      showToast("Please read and agree the Term of Use and Privacy Policy");
      return false;
    } else {
      return true;
    }
  }

  loginByApple(MSGlobalUserController controller) async {
    if (checkIsAgree()) {
      showLoading();
      try{
        final credential = await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
        );
        if(credential.identityToken != null){
          var response = await MSRequest().postForm<Map<String, dynamic>>(
              MSGlobalUrl.login,
              data: {"oauthType": "3", "token": credential.identityToken});
          if (response != null &&
              response["code"] == 0 &&
              response["data"] != null) {
            controller.token = response["data"]["token"];
            var user = MSUser.fromJson(response["data"]["userInfo"]);
            controller.user = user;
            MSLog.addEvent(page:MSLogPages.LoginSuccess);
            hideLoading();
            return true;
          }
        }
      }catch(e){
        hideLoading();
        return false;
      }
      }
return false;
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MSGlobalUserController>(
      builder: (BuildContext context, MSGlobalUserController controller,
          Widget? child) {
        return Scaffold(
          backgroundColor: Colors.amber,
          body: SizedBox(
            width: double.infinity,
            child: DecoratedBox(
              decoration: const BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage("images/login-bg.png"))),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: 428.w),
                    child: InkWell(
                      onTap: () async {
                        MSLog.addEvent(page:MSLogPages.QuickLogin);
                        loginByFast(controller).then((value) {
                          if (value) {
                            Navigator.of(context).pushNamed("/");
                          }
                        });
                      },
                      child: Image.asset(
                        "images/sign-fast.png",
                        width: 266.w,
                        height: 62.w,
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 25.w),
                    child: InkWell(
                      onTap: () {
                        MSLog.addEvent(page:MSLogPages.AppleLogin);
                        loginByApple(controller).then((value){
                        if (value) {
                            Navigator.of(context).pushNamed("/");
                      }
                        });
                      },
                      child: Image.asset(
                        "images/sign-apple.png",
                        width: 266.w,
                        height: 62.w,
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                  const Expanded(child: SizedBox()),
                  Padding(
                    padding: EdgeInsets.only(bottom: 60.w),
                    child: SizedBox(
                      width: 266.w,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(right: 10.w),
                            child: InkWell(
                              onTap: () => {
                                setState(() => {isAgree = !isAgree})
                              },
                              child: Image.asset(
                                isAgree
                                    ? "images/login-checked-box.png"
                                    : "images/login-check-box.png",
                                width: 16.w,
                                height: 16.w,
                              ),
                            ),
                          ),
                          Flexible(
                              child: RichText(
                            softWrap: true,
                            text: TextSpan(
                                text: "By using our App you agree with our ",
                                style: TextStyle(
                                    fontSize: 12.w, color: Colors.black),
                                children: [
                                  TextSpan(
                                    text: "Term of Use",
                                    recognizer: term
                                      ..onTap = () async {
                                        MSLog.addEvent(page:MSLogPages.ReadTerms);
                                        if (await canLaunchUrl(
                                            Uri.parse(MSGlobalUrl.userTerm))) {
                                          launchUrl(
                                              Uri.parse(MSGlobalUrl.userTerm));
                                        }
                                      },
                                    style: const TextStyle(
                                        fontWeight: FontWeight.bold,
                                        decoration: TextDecoration.underline),
                                  ),
                                  const TextSpan(text: " and "),
                                  TextSpan(
                                    text: "Privacy Policy",
                                    recognizer: privacy
                                      ..onTap = () async {
                                        MSLog.addEvent(page:MSLogPages.ReadPrivacy);
                                        if (await canLaunchUrl(
                                            Uri.parse(MSGlobalUrl.privacy))) {
                                          launchUrl(
                                              Uri.parse(MSGlobalUrl.privacy));
                                        }
                                      },
                                    style: const TextStyle(
                                        fontWeight: FontWeight.bold,
                                        decoration: TextDecoration.underline),
                                  )
                                ]),
                          ))
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
